package com.example.reception.service;

import com.example.reception.controller.dto.UserDTO;
import com.example.reception.dao.UserDao;
import com.example.reception.entity.Address;
import com.example.reception.entity.User;
import com.example.system.config.UploadFile;
import com.example.system.model.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;


/**
 * @author: adnaan
 * @create: 2023-10-22 22:07
 * @Description:
 */
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UploadFile uploadFile;

    public ApiResponse register(User user) {
        return userDao.save(user);
    }

    public ApiResponse isLoggedIn(String username) {
        Criteria criteriaName = Criteria.where("username").is(username);
        Criteria orCriteria = new Criteria();
        orCriteria.orOperator(criteriaName);
        Query query = new Query(orCriteria);
        User user = userDao.get(query);
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(username))) {
            return ApiResponse.success(user);
        } else {
            return ApiResponse.error("500", "未登录");
        }
    }

    public ApiResponse login(String username, String password) {
        // 检查账号密码是否为空
        if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
            return ApiResponse.error("400", "账号或密码不能为空");
        }

        // 查询用户
        User user = userDao.findByUsername(username);

        // 检查用户是否存在以及密码是否正确
        if (user != null && user.getPassword().equals(password)) {
            // 设置会话信息到Redis
            String sessionValue = "session:" + user.getId();
            stringRedisTemplate.opsForValue().set(user.getUsername(), sessionValue);
            // 创建并返回成功响应
            UserDTO userDTO = new UserDTO();
            userDTO.setUsername(user.getUsername());
            userDTO.setPassword(user.getPassword());

            return ApiResponse.success(userDTO);
        } else {
            // 返回错误响应
            return ApiResponse.error("500", "用户名或密码错误");
        }
    }

    public ApiResponse loginOut(String username) {
        if (Boolean.FALSE.equals(stringRedisTemplate.delete(username))) {
            return ApiResponse.error("500", "未找到session" + username);
        } else {
            return ApiResponse.success();
        }
    }

    public ApiResponse saveUser(User user) {
        Query query = new Query(Criteria.where("username").is(user.getUsername()));
        Update update = new Update();
        update.set("username", user.getUsername());
        update.set("password", user.getPassword());
        update.set("nickname", user.getNickname());
        update.set("email", user.getEmail());
        update.set("phone", user.getPhone());
        return userDao.update(query, update);
    }

    /*public ApiResponse uploadAvatar(String avatarUrl, String username) {
        Query query = new Query(Criteria.where("username").is(username));
        Update update = new Update();
        update.set("avatarUrl", avatarUrl);
        return userDao.update(query, update);
    }*/

    public ApiResponse getAddress(String username) {
        Query query = new Query(Criteria.where("username").is(username));
        User user = userDao.get(query);
        Query addressQue = new Query(Criteria.where("userId").is(user.getId()));
        return ApiResponse.success(userDao.findAddress(addressQue));
    }

    public ApiResponse updateAddress(Address address) {
        if(address.getId()!=null) {
        Update update = new Update();
        update.set("street", address.getStreet());
        update.set("detail", address.getDetail());
        update.set("zipCode", address.getZipCode());
        update.set("recipient", address.getRecipient());
        update.set("rePhone", address.getRePhone());
            Query query = new Query(Criteria.where("id").is(address.getId()));
            return userDao.updateAdr(query, update);
        }
        return userDao.saveAdr(address);
    }

    public ApiResponse delAddress(String delId) {
        Query query=new Query(Criteria.where("id").is(delId));
        return userDao.delAddress(query);
    }

    public ApiResponse uploadAvatar(MultipartFile file,String username) throws IOException {
        Query query = new Query(Criteria.where("username").is(username));
        Update update = new Update();
        update.set("avatarUrl", uploadFile.upload(file,"avatar"));
        return userDao.update(query, update);
    }

    public ApiResponse findPaginated(int currentPage, int pageSize, String userName) {
        return userDao.findPaginated(currentPage,pageSize,userName);
    }

    public ApiResponse delUser(String userId) {
        Query query=new Query(Criteria.where("id").is(userId));
        return userDao.delUser(query);
    }
}
